//签章服务器地址
const BASE_URL = "https://sign.sdhwj.com/ntkoSignServer";
//测试密码
const password = "sdhh_86987333";
//测试印章密码
const stampPassword = "111111";
//测试手写密码
const testWritingPswd = "111111";

// ntko服务器映射表
const ntkoServerMap = {
  '3733': 'https://xxsign.sdhwj.com/ntkoSignServer',
  '3750': 'https://hksign.sdhwj.com/ntkoSignServer',
  '3757': 'https://bzsign.sdhwj.com/ntkoSignServer',
  '3751': 'https://dpsign.sdhwj.com/ntkoSignServer',
  '3754': 'https://lcsign.sdhwj.com/ntkoSignServer',
  '3756': 'https://zbsign.sdhwj.com/ntkoSignServer',
  '3753': 'https://hzsign.sdhwj.com/ntkoSignServer',
  '3752': 'https://jnsign.sdhwj.com/ntkoSignServer',
  '3755': 'https://dzsign.sdhwj.com/ntkoSignServer'
};

// 根据本地存储的corpCode_获取ntko服务器地址
function getNtkoServerUrlFromStorage() {
  const corpCode_ = uni.getStorageSync('corpCode_');
  return ntkoServerMap[corpCode_] || BASE_URL;
}

// 基础参数
const baseParams = {
	'out-type': 'json',
	ismobile: 'true',
	lictype: '4',
	// dataType: 'json',
	deviceType: 'universe',
	licenseType: '4'
};

// 创建请求实例
const request = (url, method, data, header = null, options = {}) => {
	return new Promise((resolve, reject) => {
		// 如果是 multipart/form-data，需要特殊处理
		if (header && header['Content-Type'] === 'multipart/form-data') {
			const boundary = '----WebKitFormBoundary' + Math.random().toString(36).substring(2);
			header['Content-Type'] = `multipart/form-data; boundary=${boundary}`;
			
			// 构建 multipart/form-data 格式的数据
			let formData = '';
			for (let key in data) {
				formData += `--${boundary}\r\n`;
				formData += `Content-Disposition: form-data; name="${key}"\r\n\r\n`;
				formData += `${data[key]}\r\n`;
			}
			formData += `--${boundary}--\r\n`;
			data = formData;
		}

		uni.request({
			url: getNtkoServerUrlFromStorage() + url,
			method,
			data,
			header: header || {
				'content-type': 'application/x-www-form-urlencoded'
			},
			success: (res) => {
				if (res.statusCode === 200) {
					resolve(res.data)
				} else {
					reject(new Error(res.data || '请求失败'))
				}
			},
			fail: (err) => {
				console.error('请求失败:', err);
				debugger
			}
		})
	})
}

// 内部工具函数
const encodeParam = (param) => {
	return encodeURIComponent(param)
}

// 创建基础请求数据
const createBaseRequestData = (username, token) => {
	return {
		...baseParams,
		username: encodeParam(username),
		password: password,
		ntkoToken: token,
		token: token
	}
}

// 创建表单字段
class FormField {
	constructor(name, value, primaryName) {
		this.name = name;
		this.value = value;
		this.primaryName = primaryName;
	}

	getContent() {
		return this.primaryName + ":" + this.value;
	}

	getValidation() {
		return this.primaryName + "=" + this.name;
	}

	static create(name, value, primaryName) {
		return new FormField(name, value, primaryName);
	}
}

// 创建表单字段集合
class FormFields {
	constructor(formId, position, value) {
		this.formId = formId;
		this.position = position;
		this.value = value;
	}

	getContent() {
		let content = "";
		for (let i = 0; i < this.value.length; i++) {
			if (content === "") {
				content = this.value[i].getContent();
			} else {
				content = content + "\n" + this.value[i].getContent();
			}
		}
		return content;
	}

	getValidation() {
		let validation = "";
		for (let i = 0; i < this.value.length; i++) {
			if (validation === "") {
				validation = this.value[i].getValidation();
			} else {
				validation = validation + ";" + this.value[i].getValidation();
			}
		}
		return validation;
	}

	static create(formId, position, value) {
		return new FormFields(formId, position, value);
	}
}

// 签章类
class SecSign {
	constructor() {
		this.token = null;
	}

	// 登录
	async login(username) {
		const data = {
			...createBaseRequestData(username, this.token),
			uri: "login?l=" + new Date().getTime()
		};
		const response = await request('/login', 'POST', data);
		if (response && response.info && response.info.token) {
			this.token = response.info.token;
		}
		return response;
	}

	// 检查是否分配印章
	async hasAssignedStamps(username) {
		const data = {
			...createBaseRequestData(username, this.token),
			uri: "getUserSignH?l=" + new Date().getTime()
		};
		return request('/hasAssignedStamps', 'POST', data);
	}

	// 获取印章列表
	async listStamps(username) {
		const data = {
			...createBaseRequestData(username, this.token),
			uri: "listsigns?l=" + new Date().getTime()
		};
		return request('/listsigns', 'POST', data);
	}

	// 添加印章签名
	async addStampSign(username, sn, formFields, addDateTime) {
		const data = {
			...createBaseRequestData(username, this.token),
			sn: sn,
			stampPassword: stampPassword,
			FormId: formFields.formId,
			unid: formFields.formId,
			position: formFields.position,
			signpass: stampPassword,
			information: "text=FormId;",
			content: "text%253A"+formFields.formId+"%250A",
			isadddate: addDateTime,
			type:1,
			action:1
		};
		return request('/dosign', 'POST', data);
	}

	// 添加手写签名
	async addHandSign(username, signature, writingPassword, formFields, addDateTime) {
		const data = {
			...createBaseRequestData(username, this.token),
			data: signature,
			formFields: formFields,
			unid: formFields.formId,
			writingPassword: writingPassword,
			position: formFields.position,
			information: encodeParam(formFields.getValidation()),
			content: encodeParam(formFields.getContent()),
			isadddate: addDateTime,
			uri: "dosignlnx?type2=" + new Date().getTime()
		};
		return request('/dosign', 'POST', data);
	}

	// 删除签名
	async deleteSignature(formId, signUNID) {
		const data = {
			deviceType: 'android',
			unid: formId,
			'out-type': 'json',
			deviceDPI: '320',
			ntkoToken: this.token,
			signunid: signUNID,
			token: this.token,
			password: 'PASSWORD',
			signpass: '111111',
			lictype: '4',
			action: '2',
			sn: '',
			ismobile: 'true',
			username: uni.getStorageSync('userName')
		};
		return request('/dosign', 'POST', data);
	}

	// 获取表单签名列表
	async listSignatures(username, bizKey) {
		const data = {
			...createBaseRequestData(username, this.token),
			unid: bizKey,
			uri: "loadMobileSignLnx?l=" + new Date().getTime()
		};
		return request('/getsigninfos', 'POST', data);
	}

	// 添加文本签名
	addTextSignature(content, username, filePath, formId, position) {
		return new Promise((resolve, reject) => {
			// 构建请求URL
			const url = BASE_URL+'/dosignfromfile';
			
			// 处理base64字符串，去掉前缀
			const base64Data = filePath.replace('data:image/png;base64,', '');
			console.log('处理后的base64数据长度:', base64Data.length);
			
			// 构建FormData
			const formData = {
				deviceType: 'android',
				unid: formId,
				'out-type': 'json',
				deviceDPI: '320',
				dataType: 'json',
				ntkoToken: this.token,
				isadddate: 'true',
				type: '3',
				content: `text:${formId}\n`,
				token: this.token,
				licenseType: '4',
				password: 'sdhh_86987333',
				signpass: '111111',
				lictype: '4',
				action: '1',
				information: 'text=FormId;',
				FormId: formId,
				position: position,
				ismobile: 'true',
				username: username
			};

			console.log('发送请求参数:', {
				url,
				formId,
				position,
				username,
				token: this.token
			});

			// 发送请求
			uni.uploadFile({
				url: url,
				filePath: filePath,
				name: 'filedata',
				formData: formData,
				success: (res) => {
					console.log('请求成功，响应数据:', res);
					if (res.statusCode === 200) {
						try {
							const result = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
							console.log('解析后的响应数据:', result);
							if (result.status && result.status.errCode === "0") {
								resolve(result);
							} else {
								reject(new Error(result.status?.errMsg || '添加签名失败'));
							}
						} catch (error) {
							console.error('解析响应数据失败:', error);
							reject(new Error('解析响应数据失败'));
						}
					} else {
						console.error('请求失败，状态码:', res.statusCode);
						reject(new Error(`请求失败: ${res.statusCode}`));
					}
				},
				fail: (err) => {
					console.error('请求发送失败:', err);
					reject(err);
				}
			});
		});
	}
}

export default new SecSign(); 

// 导出getNtkoServerUrlFromStorage方法
export { getNtkoServerUrlFromStorage }; 